try_call
Safely call a function that may fail (i.e. that may throw an exception).
Accepts 0-ary unit-typed function references, i.e. references to functions of type () -> unit.
Exceptions thrown during the call are caught and logged with a stack trace.
Changes to the database that occur during the call are rolled back when an exception is thrown.
Examples:
function fails(): unit {
list<integer>()[1]; // out of bounds
}
function succeeds(): unit {}
try_call(fails(*)) // logs an out of bounds exception message and returns false
try_call(succeeds(*)) // logs nothing, returns true
// `fn` can also be written as a lambda:
try_call(() -> { list<integer>()[1]; }) // logs an out of bounds exception message and returns false
try_call(() -> {}) // logs nothing, returns true
Parameters
- fn — the function to call
Returns
true if call returns without throwing any exceptions, false otherwise
Since
0.13.0
function try_call<T>(fn: () -> T): T?Safely call a function that may fail (i.e. that may throw an exception).
Accepts 0-ary function references, i.e. references to functions of type () -> T, and returns T?,
i.e. the return value of the reference function, or null.
Exceptions thrown during the call are caught and logged with a stack trace.
Changes to the database that occur during the call are rolled back when an exception is thrown.
Examples:
function fails(): integer {
return list<integer>()[1]; // out of bounds
}
function succeeds(): unit { return 0; }
try_call(fails(*)) // logs an out of bounds exception message and returns null
try_call(succeeds(*)) // logs nothing, returns 0
// `fn` can also be written as a lambda:
try_call(() -> list<integer>()[1]) // logs an out of bounds exception message and returns null
try_call(() -> 17) // logs nothing, returns 17
Parameters
- fn — the function to be called
Returns
the return value of fn if the call returns without throwing any exceptions, null otherwise
Since
0.13.0
function try_call<T>(fn: () -> T, default: T): TSafely call a function that may fail (i.e. that may throw an exception).
Accepts 0-ary function references, i.e. references to functions of type () -> T, and a default
value to return if the call fails.
Exceptions thrown during the call are caught and logged with a stack trace.
Changes to the database that occur during the call are rolled back when an exception is thrown.
Examples:
function fails(): integer {
return list<integer>()[1]; // out of bounds
}
function succeeds(): unit { return 0; }
try_call(fails(*), 17) // logs an out of bounds exception message and returns 17
try_call(succeeds(*), 17) // logs nothing, returns 0
// `fn` can also be written as a lambda:
try_call(() -> list<integer>()[1], 17) // logs an out of bounds exception message and returns 17
try_call(() -> 42, 17) // logs nothing, returns 42
Parameters
- fn — the function to be called
- default — the default value
Returns
the return value of fn if the call returns without throwing any exceptions, default
otherwise
Since
0.13.0